package org.bhujmandir.android.utils;


import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DBController {
	private Context context = MyApplication.getAppContext();
	private DBHandle dbHandle = new DBHandle(context);
	//private static final String TAG = "Log Activity";
	
	public DBController() {
		
	}
	
	public Cursor runQuery(String query, String[] flags){
		SQLiteDatabase db = dbHandle.getReadableDatabase();
		Cursor cursor = db.rawQuery(query, flags);
		Log.v(MyApplication.TAG, query);
		if(cursor.moveToFirst()){
			Log.v(MyApplication.TAG, "cursorNotEmpty");
		}else{
			Log.v(MyApplication.TAG, "cursorEmpty");
			
		}
		return cursor;
	}
	
	
	
	public Cursor fetchTableList() {
		String queryString = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name";
		Cursor cursor = runQuery(queryString,null);
		return cursor;
	}

	public Cursor fetchArtists() {
		String queryString = "SELECT _id,artist FROM media GROUP BY artist ORDER BY artist";
		Cursor cursor = runQuery(queryString,null);
		return cursor;
	}
	public Cursor fetchAll() {
		String queryString = "SELECT * FROM media";
		Cursor cursor = runQuery(queryString,null);
		return cursor;
	}
	public Cursor fetchKathaAlbums(){
		String queryString = "SELECT DISTINCT album As album FROM media WHERE type='Kathaa'";
		Cursor cursor = runQuery(queryString,null);
		return cursor;
	}
	
	public Cursor childCursor(String heading){
		String queryString = "SELECT _id, title FROM media WHERE album = ? AND type = 'Kathaa'";
		Cursor cursor = runQuery(queryString,new String[]{heading});
		return cursor;
	}
	
	//public Cursor fetchMedia(String type, String artist, String album, String producer){
		public Cursor fetchMedia(String type, String artist, String album, String publisher, Boolean sort){
		if(type==null){type="%";};
		if(artist==null){artist="%";};
		if(album==null){album="%";};
		if(publisher==null){publisher="%";};
		if(sort==null){sort=false;};
		
		StringBuilder queryBuilder = new StringBuilder("SELECT _id, title, album, artist FROM media WHERE type LIKE '");
		queryBuilder.append(type);
		queryBuilder.append("' AND artist LIKE '");
		queryBuilder.append(artist);
		queryBuilder.append("' AND album LIKE '");
		queryBuilder.append(album);
		queryBuilder.append("' AND publisher LIKE '");
		queryBuilder.append(publisher);
		queryBuilder.append("'");
		if(sort){queryBuilder.append(" ORDER BY title ASC");};
		String queryString = queryBuilder.toString();

		Cursor cursor = runQuery(queryString,null);
		return cursor;
		
	}
	
	public void close() {
		dbHandle.close();
	}
}
